// http.js
import axios from 'axios'
import { Toast } from 'vant'
import router from '@/router'
import globalVariables from '@/utils/globalVariables'

// 创建 axios 实例
const service = axios.create()

service.interceptors.request.use(
  config => {
    const userInfo = globalVariables.getUserInfo()
    config.headers['appFlag'] = 'zhqy'
    config.headers['token'] = userInfo.token
    config.headers['customerID'] = userInfo.customerID
    config.headers['userCode'] = userInfo.userCode
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

const responseErrorCallback = error => {
  if (error.response) {
    Toast('系统繁忙，请稍后再试')
    if (error.response.status === 404) {
      // todo 跳转到404页面
    }
  }
  return Promise.reject(error)
}

const responseSuccessCallback = response => {
  const { data } = response
  if (data.error && data.error.code === 141018) {
    Toast('登录已过期')
    globalVariables.setUserInfo('')
    router.push('/')
  }
  return data
}

service.interceptors.response.use(
  responseSuccessCallback,
  responseErrorCallback
)

export { service as axios }
